package com.fz.song.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;

import javax.sql.DataSource;

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {


        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);


        //定义配置
        http.authorizeRequests()
                //定义资源和角色
                //添加ant模式的配置,
                // ?匹配任意单个字符，使用*匹配0或任意数量的字符，使用**匹配0或者更多的目录。
                .antMatchers("/admin/api/**").hasRole("ADMIN")
                .antMatchers("/user/api/**").hasRole("USER")
                .antMatchers("/app/api/**").permitAll()
                //链式调用的and()返回HttpSecurity,相当于返从这个开始新的配置
                .and()
                .formLogin()
                .and()
                .rememberMe()
                .userDetailsService(userDetailsService)
                .tokenRepository(jdbcTokenRepository);

    }


    /**
     * 这个方法也支持我们配置认证用户,同时我们向spring注册 UserDetailsService 也可以实现
     *
     * @param auth
     * @throws Exception
     */
//    @Override
//    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        auth.inMemoryAuthentication()
//                .withUser("test").password("$2a$10$9V22q06joNdW6w9kWVjhveyLIiVeMcit0TfHy0ZrsI6COI8sjwLLW").roles("TEST")
//                .and()
//                .withUser("test2").password("$2a$10$9V22q06joNdW6w9kWVjhveyLIiVeMcit0TfHy0ZrsI6COI8sjwLLW").roles("TEST");
//    }


    //    @Override
//    protected void configure(HttpSecurity http) throws Exception {
//        http
//                .authorizeRequests()
//                .anyRequest()
//                .authenticated()
//                .and()
//                .formLogin()
//                .loginPage("/login.html")
//                .loginProcessingUrl("/login")
//                .permitAll()
//                .successHandler(new AuthenticationSuccessHandler() {
//                    @Override
//                    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
//                        String name = authentication.getName();
//                        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
//
//                        System.out.println("name = " + name);
//                        System.out.println("authorities = " + authorities);
//
//                        response.setContentType("application/json;charset=utf-8");
//                        PrintWriter writer = response.getWriter();
//                        writer.write("{\"code\": \"200\",\"msg\": \"登录成功\"}");
//                        writer.flush();
//                        writer.close();
//                    }
//                })
//                .failureHandler(new AuthenticationFailureHandler() {
//                    @Override
//                    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
//                        response.setContentType("application/json;charset=utf-8");
//                        PrintWriter writer = response.getWriter();
//                        String message = e.getMessage();
//                        writer.write("{\"code\": \"-1\",\"msg\": \""+message+"\"}");
//                        writer.flush();
//                        writer.close();
//                    }
//                })
//                .and()
//                .csrf()
//                .disable();
//    }


}
